﻿using System;
using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Model.SchedulerModels;
using LiteDB;
using Sunny.UI;

namespace DevelopTool.Bll.SchedulerBlls
{
    public class Scheduler_SqlBll
    {
        public Scheduler_SqlBll()
        {
            using (var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<Scheduler_Sql>();
                col.EnsureIndex(x => x.SchedulerId);
                col.EnsureIndex(x => x.CreateTime);
                col.EnsureIndex(x => x.Id);
            }
        }



        /// <summary>
        /// 根据定时任务id获取sql任务信息
        /// </summary>
        /// <param name="codeId"></param>
        /// <returns></returns>
        public Scheduler_Sql GetBySchedulerId(int schedulerId)
        {
            using (var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<Scheduler_Sql>();

                var scheduler_Sql = col.FindOne(it => it.SchedulerId == schedulerId);

                //解压缩内容
                if (scheduler_Sql != null && !string.IsNullOrEmpty(scheduler_Sql.Sql))
                    scheduler_Sql.Sql = scheduler_Sql.Sql.GZipDecompress();

                return scheduler_Sql;

            }
        }



        /// <summary>
        /// 保存定时任务-sql任务信息
        /// </summary>
        /// <param name=></param>
        /// <returns></returns>
        public Scheduler_Sql Save(Scheduler_Sql scheduler_Sql)
        {
            using (var db = new LiteDatabase(LiteDbContext.ConnectionString))
            {
                var col = db.GetCollection<Scheduler_Sql>();

                //压缩内容
                if (!string.IsNullOrEmpty(scheduler_Sql.Sql))
                    scheduler_Sql.Sql = scheduler_Sql.Sql.GZipCompress();

                scheduler_Sql.UpdateTime = DateTime.Now;
                col.Upsert(scheduler_Sql);

                return scheduler_Sql;
            }
        }


    }
}
